<template>
  <div class="outing-container">
    <!-- 页面标题和统计卡片 -->
    <div class="page-header">
      <h2 class="page-title">老人外出关怀</h2>
      <p class="page-subtitle">用心守护每一次外出，让关爱如影随形</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <i class="el-icon-sunny"></i>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalOutings }}</div>
            <div class="stat-label">本月外出申请</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <i class="el-icon-time"></i>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.pendingOutings }}</div>
            <div class="stat-label">待审批申请</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <i class="el-icon-check"></i>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.approvedOutings }}</div>
            <div class="stat-label">已批准外出</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <i class="el-icon-user"></i>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.currentOutings }}</div>
            <div class="stat-label">当前外出中</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 操作区域 -->
    <div class="action-area">
      <div class="action-left">
        <el-button type="primary" @click="openAdd()" class="add-btn">
          <i class="el-icon-plus"></i>
          记录外出安排
        </el-button>
        <el-button @click="refreshData" class="refresh-btn">
          <i class="el-icon-refresh"></i>
          刷新数据
        </el-button>
      </div>
      <div class="action-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索老人姓名或外出事由..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable>
          <el-option label="全部状态" value=""></el-option>
          <el-option label="待审批" :value="0"></el-option>
          <el-option label="已批准" :value="1"></el-option>
          <el-option label="外出中" :value="2"></el-option>
          <el-option label="已返回" :value="3"></el-option>
          <el-option label="已取消" :value="4"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 外出申请表格 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="filteredTableData" 
        row-key="outingId"
        v-loading="loading"
        class="outing-table"
      >
        <el-table-column prop="elderName" label="老人姓名" width="120">
          <template #default="{ row }">
            <div class="elder-info">
              <div class="elder-name">{{ row.elderName }}</div>
              <div class="elder-status" :class="getStatusClass(row.elderStatus)">
                {{ getStatusText(row.elderStatus) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="外出事由" min-width="200">
          <template #default="{ row }">
            <div class="reason-text">{{ row.reason }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="expectReturn" label="预计返回时间" width="180">
          <template #default="{ row }">
            <div class="time-info">
              <div class="expect-time">{{ formatTime(row.expectReturn) }}</div>
              <div class="duration" v-if="row.status === 2">
                已外出 {{ calculateDuration(row.actualOutTime) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="申请状态" width="120">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusTagType(row.status)" 
              effect="light"
              class="status-tag"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary" 
              link
              @click="viewDetails(row)"
            >
              <i class="el-icon-view"></i>
              查看详情
            </el-button>
            <el-button 
              v-if="row.status === 0" 
              size="small" 
              type="success" 
              link
              @click="approveOuting(row)"
            >
              <i class="el-icon-check"></i>
              批准外出
            </el-button>
            <el-button 
              v-if="row.status === 2" 
              size="small" 
              type="warning" 
              link
              @click="markReturned(row)"
            >
              <i class="el-icon-back"></i>
              标记返回
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增外出申请弹窗 -->
    <el-dialog 
      v-model="show" 
      title="记录外出安排" 
      width="600px"
      class="outing-dialog"
    >
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="选择老人" prop="elderId">
          <el-select v-model="form.elderId" placeholder="请选择老人" style="width: 100%">
            <el-option
              v-for="elder in myElders"
              :key="elder.elderId"
              :label="elder.name"
              :value="elder.elderId"
            >
              <div class="elder-option">
                <span>{{ elder.name }}</span>
                <el-tag size="small" :type="getStatusTagType(elder.status)">
                  {{ getStatusText(elder.status) }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="外出事由" prop="reason">
          <el-input 
            v-model="form.reason" 
            type="textarea" 
            :rows="3" 
            placeholder="请详细描述外出事由，如：家属探望、医院复诊、外出散步等"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="预计返回时间" prop="expectReturn">
          <el-date-picker 
            v-model="form.expectReturn" 
            type="datetime" 
            placeholder="选择预计返回时间"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="注意事项">
          <el-input 
            v-model="form.notes" 
            type="textarea" 
            :rows="2" 
            placeholder="请填写外出注意事项，如：需要携带的药物、特殊护理需求等"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submit" :loading="submitting">
          提交外出安排
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog 
      v-model="detailVisible" 
      :title="`${selectedOuting?.elderName}的外出详情`"
      width="700px"
    >
      <div class="outing-detail" v-if="selectedOuting">
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="老人姓名">{{ selectedOuting.elderName }}</el-descriptions-item>
            <el-descriptions-item label="外出事由">{{ selectedOuting.reason }}</el-descriptions-item>
            <el-descriptions-item label="申请时间">{{ formatTime(selectedOuting.applyTime) }}</el-descriptions-item>
            <el-descriptions-item label="预计返回">{{ formatTime(selectedOuting.expectReturn) }}</el-descriptions-item>
            <el-descriptions-item label="实际外出" v-if="selectedOuting.actualOutTime">
              {{ formatTime(selectedOuting.actualOutTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="实际返回" v-if="selectedOuting.actualReturnTime">
              {{ formatTime(selectedOuting.actualReturnTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="当前状态">
              <el-tag :type="getStatusTagType(selectedOuting.status)">
                {{ getStatusText(selectedOuting.status) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="detail-section" v-if="selectedOuting.notes">
          <h3>注意事项</h3>
          <div class="notes-content">{{ selectedOuting.notes }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getOutingPage, addOuting, returnOuting } from '@/api/outing'
import { elderApi} from '@/api/elder'
import { ElMessage, ElMessageBox } from 'element-plus'

const tableData = ref([])
const myElders = ref([])
const show = ref(false)
const detailVisible = ref(false)
const loading = ref(false)
const submitting = ref(false)
const searchKeyword = ref('')
const statusFilter = ref('')
const selectedOuting = ref(null)

const form = ref({
  elderId: null,
  reason: '',
  expectReturn: '',
  notes: ''
})

const stats = ref({
  totalOutings: 0,
  pendingOutings: 0,
  approvedOutings: 0,
  currentOutings: 0
})

const rules = {
  elderId: [{ required: true, message: '请选择老人', trigger: 'change' }],
  reason: [{ required: true, message: '请输入外出事由', trigger: 'blur' }],
  expectReturn: [{ required: true, message: '请选择预计返回时间', trigger: 'change' }]
}

// 计算属性：筛选后的表格数据
const filteredTableData = computed(() => {
  let data = tableData.value
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    data = data.filter(item => 
      (item.elderName && item.elderName.toLowerCase().includes(keyword)) ||
      (item.reason && item.reason.toLowerCase().includes(keyword))
    )
  }
  
  // 状态筛选
  if (statusFilter.value !== '') {
    data = data.filter(item => item.status === parseInt(statusFilter.value))
  }
  
  return data
})

// 加载数据
const load = async () => {
  loading.value = true
  try {
    // 加载外出申请数据
    const res = await getOutingPage({ current: 1, size: 100 })
    tableData.value = res.data.records
    
    // 加载护工负责的老人
    const eldersRes = await elderApi.getElders()
    myElders.value = eldersRes.data
    
    // 计算统计数据
    calculateStats()
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 计算统计数据
const calculateStats = () => {
  const data = tableData.value
  stats.value = {
    totalOutings: data.length,
    pendingOutings: data.filter(item => item.status === 0).length,
    approvedOutings: data.filter(item => item.status === 1).length,
    currentOutings: data.filter(item => item.status === 2).length
  }
}

// 打开新增弹窗
const openAdd = () => {
  form.value = {
    elderId: null,
    reason: '',
    expectReturn: '',
    notes: ''
  }
  show.value = true
}

// 提交外出申请
const submit = async () => {
  try {
    submitting.value = true
    await addOuting(form.value)
    ElMessage.success('外出安排已提交')
    show.value = false
    load()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 查看详情
const viewDetails = (row) => {
  selectedOuting.value = row
  detailVisible.value = true
}

// 批准外出
const approveOuting = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要批准${row.elderName}的外出申请吗？`,
      '批准外出',
      {
        confirmButtonText: '确定批准',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 使用returnOuting API来更新状态
    await returnOuting({
      outingId: row.outingId,
      status: 1,
      actualOutTime: new Date()
    })
    
    ElMessage.success('外出申请已批准')
    load()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 标记返回
const markReturned = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要标记${row.elderName}已返回吗？`,
      '标记返回',
      {
        confirmButtonText: '确定返回',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 使用returnOuting API来更新状态
    await returnOuting({
      outingId: row.outingId,
      status: 3,
      actualReturnTime: new Date()
    })
    
    ElMessage.success('已标记返回')
    load()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 刷新数据
const refreshData = () => {
  load()
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 计算外出时长
const calculateDuration = (startTime) => {
  if (!startTime) return ''
  const start = new Date(startTime)
  const now = new Date()
  const diff = now - start
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  return `${hours}小时${minutes}分钟`
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    0: 'warning',  // 待审批
    1: 'success',  // 已批准
    2: 'primary',  // 外出中
    3: 'info',     // 已返回
    4: 'danger'    // 已取消
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审批',
    1: '已批准',
    2: '外出中',
    3: '已返回',
    4: '已取消'
  }
  return texts[status] || '未知状态'
}

// 获取老人状态类名
const getStatusClass = (status) => {
  const classes = {
    0: 'status-in',      // 在养老院
    1: 'status-out',     // 外出
    2: 'status-discharged' // 已出院
  }
  return classes[status] || 'status-unknown'
}

// 获取老人状态文本
const getElderStatusText = (status) => {
  const texts = {
    0: '在养老院',
    1: '外出中',
    2: '已出院'
  }
  return texts[status] || '未知状态'
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

onMounted(async () => {
  try {
    // 加载外出申请数据
    const res = await getOutingPage({ current: 1, size: 100 })
    tableData.value = res.data.records
    
    // 加载护工负责的老人
    const eldersRes = await elderApi.getElders()
    myElders.value = eldersRes.data
    
    // 计算统计数据
    calculateStats()
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
})
</script>

<style scoped>
.outing-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 8px;
  font-weight: 600;
}

.page-subtitle {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-card:nth-child(1) .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card:nth-child(2) .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-card:nth-child(3) .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card:nth-child(4) .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.action-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.action-left {
  display: flex;
  gap: 10px;
}

.add-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
}

.refresh-btn {
  border-radius: 8px;
  padding: 10px 20px;
}

.action-right {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.table-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.outing-table {
  border-radius: 8px;
  overflow: hidden;
}

.elder-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.elder-name {
  font-weight: 600;
  color: #2c3e50;
}

.elder-status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  width: fit-content;
}

.status-in {
  background: #e8f5e8;
  color: #27ae60;
}

.status-out {
  background: #fff3cd;
  color: #856404;
}

.status-discharged {
  background: #f8d7da;
  color: #721c24;
}

.status-unknown {
  background: #e9ecef;
  color: #6c757d;
}

.reason-text {
  line-height: 1.4;
  color: #5a6c7d;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.expect-time {
  font-weight: 500;
  color: #2c3e50;
}

.duration {
  font-size: 12px;
  color: #e74c3c;
  background: #ffeaea;
  padding: 2px 6px;
  border-radius: 4px;
  width: fit-content;
}

.status-tag {
  font-weight: 500;
}

.elder-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.outing-dialog .el-dialog__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px 8px 0 0;
}

.outing-dialog .el-dialog__title {
  color: white;
}

.outing-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  color: #2c3e50;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e8e8e8;
}

.notes-content {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #667eea;
  line-height: 1.6;
  color: #5a6c7d;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .action-area {
    flex-direction: column;
    align-items: stretch;
  }
  
  .action-right {
    justify-content: space-between;
  }
  
  .search-input {
    width: 100%;
  }
}

/* 动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.stat-card {
  animation: fadeInUp 0.6s ease;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
